<?php

namespace App\Listener;

use App\Constants\ErrorCode;
use App\Event\HangupCallEvent;
use App\Event\HangupVideoEvent;
use App\Event\InviteEvent;
use App\Event\PubMomentEvent;
use App\Event\RechargeEvent;
use App\Event\UserChatEvent;
use App\Helpers\ConfigUtil;
use App\Model\CallBase;
use App\Model\DailyTaskLog;
use App\Model\Message;
use App\Model\Moment;
use App\Model\PayOrder;
use App\Model\TaskProgressDay;
use App\Model\User;
use App\Model\UserMsgLog;
use App\Model\UserProfile;
use App\Model\VideoCall;
use App\Model\VoiceCall;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;

/**
 * 每日任务监听
 * @Listener 
 */
class DailyTaskListener implements ListenerInterface
{
    public function listen(): array
    {
        return [
            //聊天事件
            UserChatEvent::class,
            //语聊挂断事件
            HangupCallEvent::class,
            //视频挂断事件
            HangupVideoEvent::class,
            //充值事件
            RechargeEvent::class,
            //注册邀请
            InviteEvent::class,
            //发布动态
            PubMomentEvent::class
        ];
    }

    /**
     * @param UserRegistered $event
     */
    public function process(object $event)
    {
        $taskDone = false;
        switch ($event->eventType) {
                //语聊电话
            case 'hangup_call':
                $userId = [$event->answerUserId, $event->userId];
                $callType = $event->callType;
                break;
                //视频电话
            case 'hangup_video':
                $userId = [$event->answerUserId, $event->userId];
                $callType = $event->callType;
                break;
                //充值
            case 'recharge':
                $userId = $event->userId;
                $profile = UserProfile::getProfile($userId);
                $taskDone = $this->process_recharge($userId, $profile->role);
                break;
                //发布动态
            case 'moment':
                $userId = $event->userId;
                $profile = UserProfile::getProfile($userId);
                $taskDone = $this->process_moment($userId, $profile->role);
                break;
                //注册邀请
            case 'invite':
                $userId = $event->inviteUserId;
                $taskDone = $this->process_invite($userId, $event->inviteProfile);
                break;
        }

        //挂断语音和视频
        if (in_array($event->eventType, ['hangup_call', 'hangup_video'])) {
            //接听方
            $answerProfile = UserProfile::getProfile($event->answerUserId);
            //呼叫方
            $callProfile = UserProfile::getProfile($event->userId);
            //接听电话奖励
            $this->process_hangup_answer($event->answerUserId, $answerProfile->role, $callType);
            //拨打电话奖励
//            if ('daily_free_host' == $callType) {
//                return;
////                $this->z($event->userId, $callProfile->role, $callType);
//            } else {
                $this->process_hangup_call($event->userId, $callProfile->role, $callType);
//            }
        }
    }

    /**
     * 发送未完成提示
     * @param $userId
     * @param $taskId
     * @param $completeness
     * @return void
     */
    private function sendTip($userId, $taskId, $completeness): void
    {
        switch ($taskId){
            case 7:
                $name = '速配通话';
                break;
            case 6:
                $name = '视频通话';
                break;
            case 3:
                $name = '语音通话';
                break;
            default:
                return;
        }

        $task = DailyTaskLog::getTask($taskId);
        if (!$task){
            return;
        }

        if ($completeness <= 0.5){
            return;
        }

        $todayTask = DailyTaskLog::checkTodayTask($userId, $taskId);
        if ($todayTask){
            return;
        }

        $coin = $task['reward'];

        //发送透传消息
        Message::sendSlient($userId,'DAILY_TASK_TIP',[
            'title' => $name.'奖励'.$coin.'金币',
            'task_id' => $taskId,
            'sub_title' => '距离奖励还差一点哦，继续通话即可领取奖励～',
            'button_text' => '查看任务进度'
        ]);
    }

    /**
     * 发送完成提示
     * @param $userId
     * @param $taskId
     * @return void
     */
    private function sendReceive($userId,$taskId): void
    {
        switch ($taskId){
            case 7:
                $name = '速配通话';
                break;
            case 6:
                $name = '视频通话';
                break;
            case 3:
                $name = '语音通话';
                break;
            default:
                return;
        }

        $task = DailyTaskLog::getTask($taskId);
        if (!$task){
            return;
        }
        $coin = $task['reward'];

        Message::sendSlient($userId,'DAILY_TASK_FINISH_TIP',[
            'title' => '恭喜你完成任务'.$name,
            'task_id' => $taskId,
            'sub_title' => '可领取'.$coin.'金币,金币可以提现。',
            'coin' => $coin
        ]);
    }

    /**
     * 聊天
     */
    public function process_chat($userId, $role)
    {
        $done = false;
        $msgNumLmt = ConfigUtil::getDailyTasks('msg_num_lmt');
        //当天发送消息数
        $dt = date('Y-m-d');
        $msgNum = UserMsgLog::getSendMsgNum($userId, 0, $dt);

        #更新完成进度
        TaskProgressDay::addRecord($userId,DailyTaskLog::getTaskId('msg', $role),$msgNum);

        if ($msgNum >= $msgNumLmt && $msgNum < ($msgNumLmt + 10)) {
            $result = DailyTaskLog::addLog($userId, DailyTaskLog::getTaskId('msg', $role));
            $done = $result ? true : false;
        }

        log_info(__CLASS__ . "==process_chat==UserId:{$userId}==MsgNum:=={$msgNum}");
        return $done;
    }

    /**
     * 接听电话
     */
    public function process_hangup_answer($answerUserId = 0, $role = 1, $calltype = 'call')
    {
        $callCls = $calltype == 'call' ? VoiceCall::class : VideoCall::class;
        $answerDuration = $callCls::sumTotalCallTime($answerUserId, false, date('Y-m-d'), 'min');
        $callDuration = $callCls::sumTotalCallTime($answerUserId, true, date('Y-m-d'), 'min');

        $data = $answerDuration + $callDuration;
        $durationLmt = ConfigUtil::getDailyTasks('answer_lmt');
        log_info(__METHOD__ . "==UserId:{$answerUserId}==AnswerDuration:{$data}分钟");

        $taskId = DailyTaskLog::getTaskId($calltype, $role);
        #更新完成进度
        TaskProgressDay::addRecord($answerUserId,$taskId,$data);
        $this->sendTip($answerUserId, $taskId, ($data / ($durationLmt / 60)));

        if ($data < ($durationLmt / 60)) {
            return false;
        }
        //加入接听任务
        $result = DailyTaskLog::addLog($answerUserId, $taskId);
        if ($result){
            $this->sendReceive($answerUserId,$taskId);
        }
        return (bool)$result;
    }

    /**
     * 拨打电话
     */
    public function process_hangup_call($userId = 0, $role = 1, $calltype = 'call')
    {
        $callCls = $calltype == 'call' ? VoiceCall::class : VideoCall::class;
        if ($role == 1){
            $data = $callCls::sumTotalCallTime($userId, true, date('Y-m-d'), 'min');
        }else{
            $call = $callCls::sumTotalCallTime($userId, true, date('Y-m-d'), 'min');
            $answer = $callCls::sumTotalCallTime($userId, false, date('Y-m-d'), 'min');

            $data = $call + $answer;
        }

        $durationLmt = $role == 1 ? ConfigUtil::getDailyTasks('call_lmt') : ConfigUtil::getDailyTasks('answer_lmt');
        log_info(__METHOD__ . "==UserId:{$userId}==CallDuration:{$data}分钟");

        $taskId = DailyTaskLog::getTaskId($calltype, $role);

        #更新完成进度
        $task_total = $data;
        TaskProgressDay::addRecord($userId,$taskId,$task_total);
        $this->sendTip($userId, $taskId, ($task_total / ($durationLmt / 60)));

        if ($data < ($durationLmt / 60)) {
            return false;
        }
        //加入接听任务
        $result = DailyTaskLog::addLog($userId, $taskId);
        if ($result){
            $this->sendReceive($userId,$taskId);
        }
        return $result ? true : false;
    }

    /**
     * 主播拨打天天福利电话
     */
    public function process_call_free_host($userId = 0, $role = 1, $calltype = 'call')
    {
        if (!UserProfile::checkRoleHost($role)) {
            log_info(__METHOD__ . "==NotHost==UserId:{$userId}==Calltype:{$calltype}");
            return false;
        }
        //今天已拨打的福利电话数量
        $callNum = CallBase::getHostFreeCallNum($userId, date('Y-m-d'), VideoCall::CALL_TYPE);
        $numLmt = ConfigUtil::getDailyTasks('host_free_call_lmt');
        log_info(__METHOD__ . "==UserId:{$userId}==Calltype:{$calltype}==CallNum:{$callNum}==NumLmt:{$numLmt}");

        $taskId = DailyTaskLog::getTaskId($calltype, $role);

        #更新完成进度
        TaskProgressDay::addRecord($userId,$taskId,$callNum);
        $this->sendTip($userId, $taskId, ($callNum / $numLmt));

        if ($callNum < $numLmt) return false;

        //加入福利呼叫任务
        $result = DailyTaskLog::addLog($userId, $taskId);
        if ($result){
            $this->sendReceive($userId,$taskId);
        }
        return $result ? true : false;
    }

    /**
     * 充值
     */
    public function process_recharge($userId = 0, $role)
    {
        $payOrder = PayOrder::checkSuccessAmountCoin($userId, date('Y-m-d'));
        $amount = (int)$payOrder['amount'] ;//获取充值总金额
        $totalCoin = (int)$payOrder['recharge_coin']+ (int)$payOrder['send_coin'];
        $amountLmt = ConfigUtil::getDailyTasks('pay_amount_lmt');

        #更新完成进度
        TaskProgressDay::addRecord($userId,DailyTaskLog::getTaskId('recharge', $role),$totalCoin);

        if ($amount < $amountLmt) return false;
        //充值任务
        $result = DailyTaskLog::addLog($userId, DailyTaskLog::getTaskId('recharge', $role));
        return $result ? true : false;
    }

    /**
     * 发布动态
     */
    function process_moment($userId, $role)
    {
        $todayCtn = Moment::checkCount($userId, date('Y-m-d'));
        $momentLmt = ConfigUtil::getDailyTasks('moment_pub_lmt');
        #更新完成进度
        TaskProgressDay::addRecord($userId,DailyTaskLog::getTaskId('moment', $role),$todayCtn);
        if ($todayCtn < $momentLmt) return $todayCtn;
        //加入动态任务
        $result = DailyTaskLog::addLog($userId, DailyTaskLog::getTaskId('moment', $role));
        return $todayCtn;
    }

    /**
     * 注册邀请
     */
    function process_invite($userId, $userProfile)
    {

        $result = DailyTaskLog::addLog($userId, DailyTaskLog::getTaskId('invite', $userProfile->role));
        #更新完成进度
        $task_total = "task_total + 1";
        TaskProgressDay::addRecord($userId,DailyTaskLog::getTaskId('invite', $userProfile->role),$task_total);
        return $result ? true : false;
    }
}
